// subPages/mine/profile/profile.js
//login.js
//获取应用实例
const app = getApp()
var util =  require('../../../utils/util.js');
Page({
  
  data: {
    btnTxt: '确认',
    sexArray: ["男", "女"],
    region: ['请选择', '请选择', '请选择'],
    customItem: '请选择',
    communityDisabled: true,
    downImg: '/resources/login/triangleDown.png',
    upImg: '/resources/login/triangleUp.png',
    flag : false,
    codeDis : false,
    phoneCode : "获取验证码",
    isPhone: false,
    phoneTxt: '更换'
  },

  onLoad: function () {
    // console.log(app.globalData.userInfo)
    if (!app.globalData.userInfo) {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      app.userInfoReadyCallback = userInfo => {
        if (userInfo != '') {
          this.setData({
            userInfo: userInfo
          });
        }
      }
    }else{
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
    this.setData({
      sexImgSrc: this.data.downImg,
      dateImgSrc: this.data.downImg,
      regionImgSrc: this.data.downImg,
      communityImgSrc: this.data.downImg
    })
    if(app.globalData.userId){
      this.setData({
        userId: app.globalData.userId
      })
      this.getData()
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          this.setData({
            userId: userId
          });
          this.getData()
        }
      }
    }
  },

  //授权登录
  unLoginBtn:function(){
    var that = this
    if(app.globalData.userInfo){
      that.setData({
        userInfo: app.globalData.userInfo
      })
    }else{
      let isLogin = app.globalData.userId?true:false 
      //未授权
      wx.navigateTo({
        url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ isLogin,
      })
    }
  },

  //获取资料
  getData:function(){
    var that = this
    util.getAjax(app.globalData.apiUrl +'/get_user_info',function(res){
      // console.log(res)
      if(res.data){
        that.setData({
          isRegion: true,
          isSex: true,
          isDate: true,
          isCommunity: true,
          name: res.data.name,
          sexIndex: res.data.sex=='男'?0:1,
          sex: res.data.sex,
          date: res.data.birthday,
          region: [res.data.sheng,res.data.shi,res.data.qu],
          phone: res.data.phone
        })
        util.getAjax(app.globalData.apiUrl +'/get_community',function(communityRes){
          // console.log(communityRes)
          if(communityRes.data.length!=0){
            var communityArray = []
            var index = ''
            for(var i in communityRes.data){
              communityArray.push(communityRes.data[i])
              if(communityRes.data[i].id == res.data.community_id){
                index = i
              }
            }
            that.setData({
              communityArray: communityArray,
              communityIndex: index,
              community: communityArray[index].community,
              communityDisabled: false
            })
            let getDataJson = []
            getDataJson.push(that.data.name,that.data.sex,that.data.date,that.data.region,that.data.communityArray[that.data.communityIndex].id,that.data.phone)
            that.setData({
              getDataJson: JSON.stringify(getDataJson)
            })
          }
        },{sheng:res.data.sheng,shi:res.data.shi,qu:res.data.qu})
        
      }
    },{user_id: that.data.userId})
  },

  //picker
  bindSexChange: function (e) {
    this.setData({
      sexIndex: e.detail.value,
      sex: this.data.sexArray[e.detail.value],
      sexImgSrc: this.data.downImg,
      isSex: true
    })
  },

  bindSexCancel:function(){
    this.setData({
      sexImgSrc: this.data.downImg
    })
  },

  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value,
      dateImgSrc: this.data.downImg,
      isDate: true
    })
  },

  bindDateCancel:function(){
    this.setData({
      dateImgSrc: this.data.downImg
    })
  },

  //地区选择
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value,
      regionImgSrc: this.data.downImg,
      isRegion: true
    })
    this.getCommunity(this.data.region)
  },

  bindRegionCancel:function(){
    this.setData({
      regionImgSrc: this.data.downImg
    })
  },

  //社区选择
  bindCommunityChange:function(e){
    // console.log(e)
    if(this.data.communityArray){
      this.setData({
        communityIndex: e.detail.value,
        community: this.data.communityArray[e.detail.value],
        communityImgSrc: this.data.downImg,
        isCommunity: true
      })
    }
  },

  bindCommunityCancel:function(){
    this.setData({
      communityImgSrc: this.data.downImg
    })
  },

  //选择箭头
  imgChange:function(e)
  {
    var that = this
    if(e.currentTarget.dataset.type == "性别")
    {
      if(that.data.sexImgSrc == that.data.downImg)
      {
        that.setData({
          sexImgSrc: that.data.upImg
        })
      }
    }
    else if(e.currentTarget.dataset.type == "日期"){
      if(that.data.dateImgSrc == that.data.downImg)
      {
        that.setData({
          dateImgSrc: that.data.upImg
        })
      }
    }
    else if(e.currentTarget.dataset.type == "地区"){
      if(that.data.regionImgSrc == that.data.downImg)
      {
        that.setData({
          regionImgSrc: that.data.upImg
        })
      }
    }
    else if(e.currentTarget.dataset.type == "社区"){
      if(!that.data.communityDisabled){
        if(that.data.communityImgSrc == that.data.downImg)
        {
          that.setData({
            communityImgSrc: that.data.upImg
          })
        }
      }else{
        util.showModal('提示','请先选择您所在的地区')
      }
      
    }
  },

  //获取电话
  phoneInput:function(e){
    let value = e.detail.value
    this.setData({
        phone : value
    })
  },

  //获取社区数据
  getCommunity:function(region){
    var that = this
    wx.request({
      url: app.globalData.apiUrl + '/get_community', 
      data: {
        sheng: region[0],
        shi: region[1],
        qu: region[2],
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data.length!=0){
          var communityArray = []
          for(var i in res.data){
            communityArray.push(res.data[i])
          }
          that.setData({
            communityArray: communityArray,
            communityDisabled: false
          })
        }else{
          util.showModal('提示','您所选择的地区没有覆盖社区，请重新选择')
          that.setData({
            communityArray: [],
            isCommunity: false
          })
        }
      },
      fail: function (res) {
        util.showModal('提示','获取小区失败')
        return
      }
    })
  },

  //更换手机号
  isPhone:function(){
    if(this.data.isPhone){
      this.setData({
        isPhone: false,
        phoneTxt: '更换'
      })
    }else{
      this.setData({
        isPhone: true,
        phoneTxt: '取消'
      })
    }
    
  },

  //获取验证码
  smsBtn: function (options) {
    var that = this
    var phone = that.data.phone
    if(that.validationPhone(phone))
    {
      that.setData({
        codeDis : true
      })
      wx.request({
        url: app.globalData.apiUrl +'/Api/Alidayu/alyzm',
        data: {
          mobile: phone
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code != "ok"){
            that.setData({
              phoneCode : "",
              flag : true,
              codeDis : false
            })
            util.showToast('获取验证码失败，请重新获取','none',2000)
          }
          else{
            that.setData({
              phoneCode : 60,
              code: res.data.log
            })
            let time = setInterval(()=>{
              var phoneCode = that.data.phoneCode
              phoneCode --
              that.setData({
                  phoneCode : phoneCode
              })
              if(phoneCode == 0){
                clearInterval(time)
                that.setData({
                  phoneCode : "获取验证码",
                  flag : true,
                  codeDis : false
                })
              }
            },1000)
          }
        },
        fail: function (res) {
          console.log("失败");
          that.setData({
            phoneCode : "",
            flag : true,
            codeDis : false
          })
          util.showToast('获取验证码失败，请重新获取','none',2000)
        }
      })
    }
  },

  //验证手机号
  validationPhone:function(phone){
    if(!phone)
    {
      util.showModal('提示','手机号不能为空')      
      return false
    }
    if (phone.length === 11) {
      var type = 'phone'
      var validation = util.validation(phone,type)
      if(validation){
        return true
      }
      else{
        util.showModal('提示','手机号输入不正确')
        return false
      }
    }else{
      util.showModal('提示','手机号输入不正确')
      return false
    }
  },

  formSubmit:function(e){
    // console.log(e)
    var that = this
    var name = e.detail.value.name
    var date = e.detail.value.date
    var region = e.detail.value.region
    var community = e.detail.value.community
    var sms =  e.detail.value.sms;
    if(name != '')
    {
      var type= 'name'
      var validation = util.validation(name,type)
      if(!validation){
        util.showModal('提示','姓名输入不正确')
        return
      }
    }else{
      util.showModal('提示','请输入姓名')
      return
    }
    if(!that.data.sex){
      util.showModal('提示','请选择您的性别')
      return 
    }
    if(!date){
      util.showModal('提示','请选择您的出生年月')
      return 
    }
    for(var i in region){
      if(region[i] == '请选择'){
        util.showModal('提示','请选择地区')
        return 
      }
    }
    if(!community){
      util.showModal('提示','请选择您的所在社区')
      return 
    }
    if(that.data.isPhone){
      if(sms != ''){
        if(this.data.code!= '')
        {
          if(sms != this.data.code)
          {
            util.showModal('提示','短信验证码输入不正确，请重新输入')
            return
          }
        }
        else{
          util.showModal('提示','请获取短信验证码')
          return
        }
      }
      else{
        util.showModal('提示','短信验证码不能为空')      
        return
      }
    }else{
      that.validationPhone(that.data.phone)
    }

    let newDataJson = []
    newDataJson.push(name,that.data.sex,date,region,that.data.communityArray[that.data.communityIndex].id,that.data.phone)
    if(that.data.getDataJson == JSON.stringify(newDataJson)){
      util.showModal('提示','请修改数据后，重新保存')
      return
    }
    that.save(name,date,region,community)
  },

  //保存
  save:function(name,date,region,community){
    var that = this
    wx.request({
      url: app.globalData.apiUrl + '/save_user',
      data: {
        type: 1,
        user_id: that.data.userId,
        name: name,
        sex: that.data.sex,
        birthday: date,
        phone: that.data.phone,
        sheng: region[0],
        shi: region[1],
        qu: region[2],
        community_id: that.data.communityArray[that.data.communityIndex].id,
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data == '1'){
          util.showToast('修改成功','success',1000)
          app.globalData.communityId = that.data.communityArray[that.data.communityIndex].id
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }else{
          util.showModal('提示','修改失败，请重新保存')
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '进入失败，请重试进入',
          showCancel: false,
          complete (res) {
            that.setData({
              btnDis: false
            })
          }
        })
      }
    })
  }
})